package com.ucode.cgms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ucode.cgms.api.CgmsMemberRemoteApi;
import com.ucode.cgms.mapper.*;
import com.ucode.cgms.service.CgmsCompanionOrderService;
import com.ucode.model.cgms.CgmsCommissionFlow;
import com.ucode.model.cgms.CgmsCompanionOrder;
import com.ucode.model.cgms.CgmsJointServiceUser;
import com.ucode.model.cgms.enums.*;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.base.enums.UserTypeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class CgmsCompanionOrderServiceImpl implements CgmsCompanionOrderService {

    @Resource
    private CgmsCompanionOrderMapper cgmsCompanionOrderMapper;
    @Resource
    private CgmsCompanionProductMapper cgmsCompanionProductMapper;
    @Resource
    private CgmsJointServiceUserMapper cgmsJointServiceUserMapper;
    @Resource
    private CgmsCompanionUserMapper cgmsCompanionUserMapper;
    @Resource
    private CgmsCommissionFlowMapper commissionFlowMapper;
    @Resource
    private CgmsMemberRemoteApi memberRemoteApi;

    @Override
    public CgmsCompanionOrderMapper initMapper() {
        return cgmsCompanionOrderMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(CgmsCompanionOrder cgmsCompanionOrder) {
        if(ObjUtil.isNull(cgmsCompanionOrder.getId())){
            cgmsCompanionOrder.setId(IdentifyUtils.getDefaultSnowflakeId());
        }
        int i = cgmsCompanionOrderMapper.insert(cgmsCompanionOrder);
        return i > 0 ? cgmsCompanionOrder.getId() : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccess(Long orderId, Long payOrderId, String payType, LocalDateTime payTime, Integer payAmount) {
        CgmsCompanionOrder companionOrder = this.validate(orderId);

        //判断订单支付状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.PENDING_PAYMENT.getCode()) &&
                !ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.CANCELLED.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_WAITING);
        }


        //判断金额
        if(NumberUtil.mul(companionOrder.getPayPrice(),100).intValue() != payAmount.intValue()){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_AMOUNT_NOT_EQUALS);
        }

        //直接找陪玩点单，直接进入待确认状态；否则进入接单中状态
        Integer statuz = ObjUtil.equals(companionOrder.getServiceUserId(), 0L) ? CgmsCompanionOrderStatusEnum.DISPATCHING.getCode() : CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode();
        cgmsCompanionOrderMapper.paySuccess(orderId, statuz,payOrderId,  payType, payTime);

        //更新服务商品销量
        cgmsCompanionProductMapper.updateIncrSalesAndDecrStock(companionOrder.getProductId(),companionOrder.getQuantity());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(Long id) {
        this.validate(id);
        int i = cgmsCompanionOrderMapper.cancel(id);
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_WAITING);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelByMember(Long userId, Long id) {
        this.validate(id,userId);
        int i = cgmsCompanionOrderMapper.cancel(id);
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_WAITING);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmCompleted(Long userId, Long id) {
        CgmsCompanionOrder companionOrder = this.validate(id,userId);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.END_SERVICE.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_END_SERVICE);
        }

        CgmsCompanionOrder updateOrder = new CgmsCompanionOrder();
        updateOrder.setId(companionOrder.getId());
        updateOrder.setReportAuditState(CgmsCompanionReportAuditStateEnum.SUCCESS.getCode());
        updateOrder.setProcessorId(userId);
        updateOrder.setProcessorType(UserTypeEnum.MEMBER.getCode());
        updateOrder.setProcessTime(LocalDateTime.now());
        updateOrder.setProcessRemark("用户确认完成");

        //计算抽成
        //抽成比例
        BigDecimal commissionRatio = ObjUtil.isNull(companionOrder.getCommissionRatio()) ? BigDecimal.ZERO : NumberUtil.div(companionOrder.getCommissionRatio(),100);

        BigDecimal payPrice = companionOrder.getPayPrice();
        if(ObjUtil.isNotNull(companionOrder.getRefundAmount())) {
            payPrice = NumberUtil.sub(payPrice,companionOrder.getRefundAmount());
        }

        //总抽成
        BigDecimal commissionAmount = NumberUtil.mul(payPrice,commissionRatio);
        updateOrder.setCommissionAmount(commissionAmount);
        //订单最终金额
        updateOrder.setFinalAmount(NumberUtil.sub(payPrice,commissionAmount));

        //confirmCompletedAfter(companionOrder);//多人分账逻辑，暂时无用

        int i = cgmsCompanionOrderMapper.confirmCompleted(updateOrder);
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_END_SERVICE);

        //陪玩单量
        cgmsCompanionUserMapper.updateIncrOrderCount(userId, 1);
    }

    /**
     * 订单完工后处理，主要分账、佣金流水处理
     * @param companionOrder
     */
    private void confirmCompletedAfter(CgmsCompanionOrder companionOrder){
        BigDecimal sourceAmount = companionOrder.getPayPrice();
        List<CgmsJointServiceUser> list = cgmsJointServiceUserMapper.queryListByOrderId(companionOrder.getId());

        //推荐人
        Long referrerId = memberRemoteApi.queryReferrerIdByMemberId(companionOrder.getMemberId());

        List<CgmsCommissionFlow> commissionFlowList = new ArrayList<>();

        //抽成比例
        BigDecimal commissionRatio = NumberUtil.div(companionOrder.getCommissionRatio(),100);
        //总抽成
        BigDecimal commissionAmount = BigDecimal.ZERO;

        //返点比例
        BigDecimal rebateRatio = NumberUtil.div(companionOrder.getRebateRatio(),100);
        //总返点
        BigDecimal rebateAmount = BigDecimal.ZERO;
        //分账处理逻辑
        if(CollUtil.isNotEmpty(list)) {

            //验证分账总金额不能大于总订单金额
            BigDecimal totalAmount = list.stream().map(CgmsJointServiceUser::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(totalAmount.compareTo(companionOrder.getPayPrice()) > 0){
                throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SUB_AMOUNT_IS_MORE_THAN_PAY_PRICE);
            }

            //判断接单用户是否有分账金额

            for(CgmsJointServiceUser bean : list){

                CgmsCommissionFlow commissionFlow = new CgmsCommissionFlow();
                commissionFlow.setId(IdentifyUtils.getDefaultSnowflakeId());
                commissionFlow.setUserId(bean.getServiceUserId());
                commissionFlow.setOrderId(bean.getOrderId());
                commissionFlow.setStatuz(CgmsCommissionStatusEnum.PENDING.getCode());
                commissionFlow.setCommissionType(CgmsCommissionTypeEnum.COMPANION_ORDER.getCode());
                commissionFlow.setOrderAmount(bean.getAmount());
                //计算返点金额
                if(ObjUtil.isNotNull(referrerId) && !ObjUtil.equals(referrerId, 0L)) {
                    commissionFlow.setReturnPointAmount(NumberUtil.mul(commissionFlow.getOrderAmount(),rebateRatio));
                }
                //计算抽成
                commissionFlow.setCommissionAmount(NumberUtil.mul(commissionFlow.getOrderAmount(),commissionRatio));
                commissionFlow.setAmount(NumberUtil.sub(commissionFlow.getOrderAmount(),commissionFlow.getCommissionAmount(),commissionFlow.getReturnPointAmount()));

                commissionFlowList.add(commissionFlow);

                commissionAmount = NumberUtil.add(commissionAmount,commissionFlow.getCommissionAmount());
                rebateAmount = NumberUtil.add(rebateAmount,commissionFlow.getReturnPointAmount());
            }

            //接单人最终分账金额
            sourceAmount = NumberUtil.sub(sourceAmount,totalAmount);
        }

        if(sourceAmount.compareTo(BigDecimal.ZERO) > 0){

            CgmsCommissionFlow commissionFlow = new CgmsCommissionFlow();
            commissionFlow.setId(IdentifyUtils.getDefaultSnowflakeId());
            commissionFlow.setUserId(companionOrder.getServiceUserId());
            commissionFlow.setOrderId(companionOrder.getId());
            commissionFlow.setStatuz(CgmsCommissionStatusEnum.PENDING.getCode());
            commissionFlow.setCommissionType(CgmsCommissionTypeEnum.COMPANION_ORDER.getCode());
            commissionFlow.setOrderAmount(sourceAmount);
            //计算返点金额
            if(ObjUtil.isNotNull(referrerId) && !ObjUtil.equals(referrerId, 0L)) {
                commissionFlow.setReturnPointAmount(NumberUtil.mul(commissionFlow.getOrderAmount(),rebateRatio));
            }
            //计算抽成
            commissionFlow.setCommissionAmount(NumberUtil.mul(commissionFlow.getOrderAmount(),commissionRatio));
            commissionFlow.setAmount(NumberUtil.sub(commissionFlow.getOrderAmount(),commissionFlow.getCommissionAmount(),commissionFlow.getReturnPointAmount()));

            commissionFlowList.add(commissionFlow);

            commissionAmount = NumberUtil.add(commissionAmount,commissionFlow.getCommissionAmount());
            rebateAmount = NumberUtil.add(rebateAmount,commissionFlow.getReturnPointAmount());
        }

        //添加返点佣金
        if(rebateAmount.compareTo(BigDecimal.ZERO) > 0){
            CgmsCommissionFlow commissionFlow = new CgmsCommissionFlow();
            commissionFlow.setId(IdentifyUtils.getDefaultSnowflakeId());
            commissionFlow.setUserId(referrerId);
            commissionFlow.setOrderId(companionOrder.getId());
            commissionFlow.setStatuz(CgmsCommissionStatusEnum.PENDING.getCode());
            commissionFlow.setCommissionType(CgmsCommissionTypeEnum.ORDER_RETURN_POINT.getCode());
            commissionFlow.setOrderAmount(companionOrder.getPrice());
            commissionFlow.setReturnPointAmount(BigDecimal.ZERO);
            commissionFlow.setCommissionAmount(BigDecimal.ZERO);
            commissionFlow.setAmount(rebateAmount);
            commissionFlowList.add(commissionFlow);
        }

        if(commissionFlowList.size() > 0)
            commissionFlowMapper.batchInsert(commissionFlowList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceive(Long id) {
        CgmsCompanionOrder companionOrder = this.validate(id);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
        }

        //校验接单用户
        if(ObjUtil.equals(companionOrder.getServiceUserId(),0L)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        //更新订单状态
        int i = cgmsCompanionOrderMapper.confirmReceive(id,LocalDateTime.now());
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceiveByMember(Long userId, Long id) {
        CgmsCompanionOrder companionOrder = this.validate(id);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
        }

        //校验接单用户
        if(!ObjUtil.equals(companionOrder.getServiceUserId(),userId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        //更新订单状态
        int i = cgmsCompanionOrderMapper.confirmReceive(id,LocalDateTime.now());
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuseReceiveByAdmin(Long id) {
        CgmsCompanionOrder companionOrder = this.validate(id);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
        }

        //校验接单用户
        if(ObjUtil.equals(companionOrder.getServiceUserId(),0L)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        int i = cgmsCompanionOrderMapper.refuseReceive(id);
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuseReceiveByMember(Long userId, Long id) {
        CgmsCompanionOrder companionOrder = this.validate(id);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.PENDING_CONFIRM.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
        }

        //校验接单用户
        if(!ObjUtil.equals(companionOrder.getServiceUserId(),userId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        int i = cgmsCompanionOrderMapper.refuseReceive(id);
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_PENDING_CONFIRM);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addJointServiceUser(Long userId,Long orderId, List<CgmsJointServiceUser> jointServiceUsers) {

        CgmsCompanionOrder companionOrder = this.validate(orderId);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_IN_SERVICE);
        }

        //校验接单用户
        if(!ObjUtil.equals(companionOrder.getServiceUserId(),userId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        Set<Long> jointServiceUserIds = CollUtil.isNotEmpty(companionOrder.getJointServiceUserIds()) ? companionOrder.getJointServiceUserIds() : new HashSet<>();

        List<CgmsJointServiceUser> list = new ArrayList<>();

        for(CgmsJointServiceUser jointServiceUser : jointServiceUsers){
            if(!ObjUtil.equals(jointServiceUser.getServiceUserId(), userId) && !jointServiceUserIds.contains(jointServiceUser.getServiceUserId())){
                jointServiceUser.setId(IdentifyUtils.getDefaultSnowflakeId());
                jointServiceUser.setOrderId(orderId);
                list.add(jointServiceUser);

                jointServiceUserIds.add(jointServiceUser.getServiceUserId());
            }
        }

        List<CgmsJointServiceUser> db_CgmsJointServiceUsers =  cgmsJointServiceUserMapper.queryListByOrderId(orderId);
        if(CollUtil.isEmpty(db_CgmsJointServiceUsers)){
            db_CgmsJointServiceUsers = new ArrayList<>();
        }
        db_CgmsJointServiceUsers.addAll(list);

        //验证分账总金额不能大于总订单金额
        BigDecimal totalAmount = db_CgmsJointServiceUsers.stream().map(CgmsJointServiceUser::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(totalAmount.compareTo(companionOrder.getPayPrice()) > 0){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SUB_AMOUNT_IS_MORE_THAN_PAY_PRICE);
        }

        if(CollUtil.isNotEmpty(list)){
            cgmsJointServiceUserMapper.batchInsert(list);

            CgmsCompanionOrder updateBean = new CgmsCompanionOrder();
            updateBean.setId(orderId);
            updateBean.setJointServiceUserIds(jointServiceUserIds);
            cgmsCompanionOrderMapper.update(updateBean);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJointServiceUser(Long userId, Long orderId, Long jointServiceUserId) {

        CgmsCompanionOrder companionOrder = this.validate(orderId);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_IN_SERVICE);
        }

        //校验接单用户
        if(!ObjUtil.equals(companionOrder.getServiceUserId(),userId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        Set<Long> jointServiceUserIds = CollUtil.isNotEmpty(companionOrder.getJointServiceUserIds()) ? companionOrder.getJointServiceUserIds() : new HashSet<>();

        CgmsJointServiceUser cgmsJointServiceUser = cgmsJointServiceUserMapper.queryOne(orderId, jointServiceUserId);

        if(ObjUtil.isNotNull(cgmsJointServiceUser))
            cgmsJointServiceUserMapper.deleteByPrimaryKey(cgmsJointServiceUser.getId());
        if(jointServiceUserIds.contains(jointServiceUserId)) {
            jointServiceUserIds.remove(jointServiceUserId);

            CgmsCompanionOrder updateBean = new CgmsCompanionOrder();
            updateBean.setId(orderId);
            updateBean.setJointServiceUserIds(jointServiceUserIds);
            cgmsCompanionOrderMapper.update(updateBean);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void companionReport(Long reportUserId, Long id, LocalDateTime serviceStartTime, LocalDateTime serviceEndTime, List<String> evidencePics, String evidenceRemark) {
        CgmsCompanionOrder companionOrder = this.validate(id);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.IN_SERVICE.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_END_SERVICE);
        }

        //校验接单用户
        if(!ObjUtil.equals(companionOrder.getServiceUserId(),reportUserId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }

        CgmsCompanionOrder updateOrder = new CgmsCompanionOrder();
        updateOrder.setId(companionOrder.getId());
        updateOrder.setServiceStartTime(serviceStartTime);
        updateOrder.setServiceEndTime(serviceEndTime);
        updateOrder.setEvidencePics(evidencePics);
        updateOrder.setEvidenceRemark(evidenceRemark);
        updateOrder.setReportAuditState(CgmsCompanionReportAuditStateEnum.AUDITING.getCode());

        int i = cgmsCompanionOrderMapper.companionReport(updateOrder);
        if(i == 0)
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_STATUS_IS_NOT_END_SERVICE);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRemark(Long id, String remark) {
        CgmsCompanionOrder companionOrder = new CgmsCompanionOrder();
        companionOrder.setId(id);
        companionOrder.setOrderNote(remark);
        return cgmsCompanionOrderMapper.update(companionOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRemarkByMember(Long userId, Long id, String remark) {
        this.validate(id,userId);
        getSelf().updateRemark(id,remark);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByMember(Long userId, Long id) {
        CgmsCompanionOrder companionOrder = this.validate(id,userId);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.CANCELLED.getCode()) &&
                !ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.AFTER_SALE_DONE.getCode()) &&
                !ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.COMPLETED.getCode())){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_DELETE_FAIL_STATUS_NOT_CANCEL);
        }
        return cgmsCompanionOrderMapper.logicDeletePrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void designateOrder(Long userId, Long orderId) {
        CgmsCompanionOrder companionOrder = this.validate(orderId);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.DISPATCHING.getCode()) || !ObjUtil.equals(companionOrder.getServiceUserId(),0L)){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SNATCH_FAIL);
        }

        if(cgmsCompanionOrderMapper.designateOrder(orderId,userId,LocalDateTime.now()) == 0){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SNATCH_FAIL);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void snatchOrder(Long userId, Long orderId) {
        CgmsCompanionOrder companionOrder = this.validate(orderId);
        //校验接单状态
        if(!ObjUtil.equals(companionOrder.getStatus(), CgmsCompanionOrderStatusEnum.DISPATCHING.getCode()) || !ObjUtil.equals(companionOrder.getServiceUserId(),0L)){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SNATCH_FAIL);
        }

        if(cgmsCompanionOrderMapper.snatchOrder(orderId,userId,LocalDateTime.now()) == 0){
            throw new UcodeServiceException(CgmsSysResultCodeEnum.COMPANION_ORDER_SNATCH_FAIL);
        }
    }

    @Override
    public List<CgmsCompanionOrder> queryCompanionUserSnatchOrderList() {
        Map<String,Object> condition = new HashMap<>();
        condition.put("status", CgmsCompanionOrderStatusEnum.DISPATCHING.getCode());
        condition.put("serviceUserId",0L);
        condition.put("deltag",false);
        return cgmsCompanionOrderMapper.queryObjectForList(condition,4);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditReport(Long id, Integer auditState, Long processorId, Integer processorType, String processRemark) {
        // 验证订单
        CgmsCompanionOrder order = this.validate(id);

        // 验证报备状态，只有报备审核中的状态才能审核
        if (order.getReportAuditState() != CgmsCompanionReportAuditStateEnum.AUDITING.getCode()) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED, "只有报备审核中的订单才能进行审核");
        }

        // 验证审核状态
        CgmsCompanionReportAuditStateEnum auditStateEnum = CgmsCompanionReportAuditStateEnum.getByCode(auditState);
        if (auditStateEnum == null) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED, "审核状态不合法");
        }

        // 更新订单信息
        CgmsCompanionOrder updateOrder = new CgmsCompanionOrder();
        updateOrder.setId(id);
        updateOrder.setReportAuditState(auditState);
        updateOrder.setProcessorId(processorId);
        updateOrder.setProcessorType(processorType);
        updateOrder.setProcessTime(LocalDateTime.now());
        updateOrder.setProcessRemark(processRemark);

        // 如果审核通过，更新报备状态和订单状态
        if (auditStateEnum == CgmsCompanionReportAuditStateEnum.SUCCESS) {
            updateOrder.setReportAuditState(CgmsCompanionReportAuditStateEnum.SUCCESS.getCode());
            updateOrder.setStatus(CgmsCompanionOrderStatusEnum.END_SERVICE.getState());
            updateOrder.setServiceEndTime(LocalDateTime.now());
        }
        // 如果审核不通过，更新报备状态
        else if (auditStateEnum == CgmsCompanionReportAuditStateEnum.REJECT) {
            updateOrder.setReportAuditState(CgmsCompanionReportAuditStateEnum.REJECT.getCode());
        }

        int rows = this.update(updateOrder);


        return rows > 0;
    }
    /**
     * 获得自身的代理对象，解决 AOP 生效问题
     *
     * @return 自己
     */
    private CgmsCompanionOrderServiceImpl getSelf() {
        return SpringUtil.getBean(getClass());
    }
}
